<template>
  <div id="content-show">
    <div v-html="content"></div>
    <!--<el-button @click="save">save</el-button>-->
    <div v-if="rightShow" class="right-menu" :style="'position: absolute; top:' + offset.y + 'px;left:' + offset.x + 'px'">
      <el-button type="text" v-if="showDelTr" @click="deleteTr">删除</el-button>
      <el-button type="text" v-if="showDelTr==false" @click="addTr" style="margin: 0">添加</el-button>
      <el-button type="text" v-if="showDelTr==false" @click="dialogVisible = true" style="margin: 0">物料</el-button>
    </div>

    <el-dialog
      title="物料选择"
      :visible.sync="dialogVisible"
      append-to-body
      @close="dialogVisible = false"
      width="900px">
      <table-ext :columns="columns" :searchForm="searchForm" :config="config" ref="tableExt">
        <template slot="table-action">
          <el-button type="primary" size="small"  @click="handleSubmit">选择</el-button>
        </template>
      </table-ext>
    
    </el-dialog>
  </div>
</template>

<script>
  import Vue from 'vue';
  import {Input, DatePicker, Select, Option} from 'element-ui';
  import DateProxy from './DateProxy';
  import TableExt from '../table-ext/table-ext';
  import $ from 'jquery';
  export default {
    props: ['content', 'elList'],
    data() {
      return {
        result: {},
        elMap: {},
        tableList: [],
        tableMap:{},
        showDelTr:true,
        rightShow: false,
        offset:{
          x: 0,
          y: 0
        },
        tempTr: null,
        dialogVisible: false,
        config:{ // 页面共通配置
          isPage: true, //是否分页
          isNo:true,
          title:'物料',
          currentRow: true,
          prefixCls: 'select',
          tableHeight: '400',
          crudMapping:{
            query:{
              url: this.lib.config.host.masterData + '/mdata/material/getMaterialByFactory',
              data:{'purOrgId':this.purOrgId,"factoryId" : this.factoryId}
              // data:{'purOrgId':this.purOrgId,"factoryId" : this.factoryId,"factoryIds" : this.factoryIds}
            }
          }
        },
        searchForm:[{ // 查询表单配置
          label: '物料编码',
          key: 'materialCode',
          type: 'input'
        },{
          label: '物料名称',
          key: 'materialName',
          type: 'input'
        }],
        columns:[{
          label: '物料编码',
          key: 'materialCode',
          order: true,
          align: 'center',
          width:'150px'
        },{
          label: '物料名称',
          key: 'materialName',
          align: 'center',
          width:'200px'
        },{
          label: '单位编码',
          key: 'purUnitCode',
          align: 'center'
        },{
          label: '单位名称',
          key: 'purUnitName',
          align: 'center',
          width:'100px'
        },{
          label: '库存单位',
          key: 'stockUnitName',
          align:'center',
          width:'100px'
        },{
          label: '集采标识',
          key: 'cpFlag',
          align:'center',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
            if(params.row.cpFlag == 1){
              return createElement('div','集采');
            } else  {
              return createElement('div','非集采');
            }
          }
        }]
      };
    },
    components: {
      DateProxy,
      TableExt
    },
    updated() {
      this.$nextTick(function () {
        this.setElList();
      })
    },
    mounted() {
      this.setElList();
    },
    created(){
      // this.content = this.$route.params.content;
      // this.elList = this.$route.params.elList;
      this.data = { //后台获取基本数据替换占位符
        mycode1: 'xxxx公司',
        mycode2: 'xxxxx供应商',
        mycode3: 'hahahahah'
      };
    },
    // mounted(){
    //   this.elList.forEach((item)=>{
    //     this.$set(this.elMap, item.elId, item);
    //     if (item.elType === 'input') {
    //       this.mounteInput(item.elId, item);
    //     } else if (item.elType === 'select') {
    //       this.mounteSelect(item.elId, item);
    //     } else if (item.elType === 'date') {
    //       this.mounteDate(item.elId, item);
    //     } else if (item.elType === 'table') {
    //         this.tableList.push(item);
    //     }
    //   });
    // },
    methods: {
      handleSubmit(){ //物料确认
        let data = this.$refs.tableExt.getCurrentRow();
        let tableId = this.tempTr.parentNode.parentNode.id;
        let com = this.tempTr.cloneNode(true);
        let thList = com.querySelectorAll('th');
        thList.forEach(th=>{
          com.removeChild(th);
        });
        let table = document.getElementById(tableId);
        let configStr = table.getAttribute('config');
        let configList = JSON.parse(configStr);
        configList.forEach(config=>{
          let val = data[config.field];
          if(config.field=='unitId'){
            val = data['purUnitId'];
          }else if(config.field=='unitCode'){
            val = data['purUnitCode'];
          }else if(config.field=='unitName'){
            val = data['purUnitName'];
          }
          let hide = config.hide == 1
          let display = hide?'display:none':'';
          let input = hide?'<input type="hidden" name="'+config.field+'"/>':'<input type="text" name="'+config.field+'"/>';
          let td = document.createElement('td');
          if(hide){
            td.style.display = 'none';
            let input = document.createElement('input');
            input.type = 'hidden';
            input.name = config.field;
            input.value =val?val:'';
            td.appendChild(input);
          }else{
            let input = document.createElement('input');
            input.type = 'text';
            input.name = config.field;
            input.value =val?val:'';
            td.appendChild(input);
          }
          com.appendChild(td);
        });
        this.tempTr.parentNode.appendChild(com);
        

        // for (let i = 0; i < tdList.length; i++) {
        //   let td =tdList[i];
        //   if (td.childNodes.length > 0) {
        //       let code = this.tableMap[tableId].headList[i];
        //       if (data[code]) {
        //         td.childNodes[0].querySelector('input').value = data[code];
        //       }
        //   }
        // }
        this.dialogVisible = false;
      },
      deleteTr(){
        this.tempTr.parentNode.removeChild(this.tempTr);
      },
      addTr(){
        let com = this.tempTr.cloneNode(true);
        let thList = com.querySelectorAll('th');
        thList.forEach(th=>{
          com.removeChild(th);
        });
        let tbId = com.getAttribute('tbid');
        let table = document.getElementById(tbId);
        let configStr = table.getAttribute('config');
        let configList = JSON.parse(configStr);
        configList.forEach(config=>{
          let hide = config.hide == 1
          let display = hide?'display:none':'';
          let input = hide?'<input type="hidden" name="'+config.field+'"/>':'<input type="text" name="'+config.field+'"/>';
          let td = document.createElement('td');
          if(hide){
            td.style.display = 'none';
            let input = document.createElement('input');
            input.type = 'hidden';
            input.name = config.field;
            td.appendChild(input);
          }else{
            let input = document.createElement('input');
            input.type = 'text';
            input.name = config.field;
            td.appendChild(input);
          }
          com.appendChild(td);
        });
        this.tempTr.parentNode.appendChild(com);
      },
      save() {
        let data = {};
        Object.keys(this.result).forEach((key) => {
          if (this.elMap[key].elField && this.elMap[key].elField !== '') {
            data[this.elMap[key].elField] = this.result[key];
          }
        });

        this.tableList.forEach((item) => {
          let headList = item.headList;
          let tableData = [];
          let tempData = {};
          let tdList = document.getElementById(item.elId).querySelectorAll('td');
          for (let i = 0; i < tdList.length; i++) {
            let td = tdList[i];
            if (!td) {
              continue;
            }
            let headIndex = (i >= headList.length)? i % headList.length : i;
            if (td.childNodes.length > 0) {
              if (td.childNodes[0].className === 'el-select') {
                tempData[headList[headIndex]] = td.childNodes[0].__vue__.value;
              } else {
                tempData[headList[headIndex]] = td.childNodes[0].querySelector('input').value;
              }
            } else if (td.innerText) {
              tempData[headList[headIndex]] = td.innerText;
            } else {
              tempData[headList[headIndex]] = '';
            }
            if (headList.length === headIndex + 1) {
              tableData.push(JSON.parse(JSON.stringify(tempData)));
              tempData = {};
            }
          }
          data[item.elField] = tableData;
        });

        // this.$notify({
        //   title: '提示',
        //   message: JSON.stringify(this.result),
        //   duration: 0
        // });
        this.$notify({
          title: '结构化数据',
          message: JSON.stringify(data),
          duration: 0
        });
      },
      setElList() {
        let _this = this;
        window.onclick=function (e) {
          _this.rightShow = false;
        };
        this.elList.forEach((item) => {
          this.$set(this.elMap, item.elId, item);
          if (item.elType === 'input' && document.getElementById(item.elId)) {
            this.mounteInput(item.elId, item);
          } else if (item.elType === 'select' && document.getElementById(item.elId)) {
            this.mounteSelect(item.elId, item);
          } else if (item.elType === 'selectUrl' && document.getElementById(item.elId)) {
            this.mounteSelectUrl(item.elId, item);
          } else if (item.elType === 'date' && document.getElementById(item.elId)) {
            this.mounteDate(item.elId, item);
          } else if (item.elType === 'table') {
            this.tableList.push(item);
            let table = document.getElementById(item.elId);
            table.setAttribute('config',item.elContent);
            this.$set(this.tableMap, item.elId, item);
            let trList = table.querySelectorAll('tr');
            for (let i = 0; i < trList.length; i++) {
              trList[i].setAttribute('tbid',item.elId);
              trList[i].oncontextmenu = function (e) {
                e.preventDefault();
                if(i==0){
                _this.showDelTr = false;
                }else{
                  _this.showDelTr = true;
                }
                _this.offset.x = e.clientX;
                _this.offset.y = e.clientY;
                _this.tempTr = this;
                _this.rightShow = true;
              }
              //处理隐藏列
              let tdList = [];
              if(i==0){
                tdList = trList[i].querySelectorAll('th');
              }else{
                tdList = trList[i].querySelectorAll('td');
              }
              tdList.forEach((td,tdIndex)=>{
              var elConfig = JSON.parse(item.elContent);
              if(elConfig[tdIndex].hide == 1){
                td.style.display = 'none';
                td.setAttribute('type','hide');
                td.setAttribute('field',elConfig[tdIndex].field);
              }});              


            }
          }
        });
      },
      mounteInput(id, item) {
        let _this = this;
        this.$set(this.result, item.elId, '');
        // let a = Vue.extend(Input);
        new Vue({
          el: '#' + id,
          parent: this,
          data:{
            value: _this.result[id],
            styleObj: {
              width:'50px'
            }
          },
          template:'<input type="text" v-model="value" :style="styleObj" @input="change"/>',
          methods:{
            change(){
               _this.result[id] = this.value;
               let width =  _this.textWidth(this.value);
               this.styleObj.width = width+'px';
            }
          }
        });
      },
      mounteSelect(id, item) {
        let _this = this;
        let options = JSON.parse(item.elContent);
        this.$set(this.result, item.elId, {});
        new Vue({
          el: '#'+id,
          parent: this,
          data:{
            value: '',
            options:options
          },
          template:'<el-select v-model="value" @change="change"><el-option v-for="item in options" :key="item.value" :label="item.value" :value="item.value"/></el-select>',
          methods:{
            change(v){
                _this.result[id] = v;
            }
          }
        });
      },
      mounteSelectUrl(id, item) {
        let _this = this;
        let config = JSON.parse(item.elFormat);
        let valueDef = 'item.value'; 
        if(config.text==item.elField){
            valueDef = 'item.text'; 
        }
        let remote = true;
        if(config.once){
            remote= false;
        }
        this.$set(this.result, item.elId, {});
          new Vue({
            el: '#' + id,
            parent: this,
            data: {
              remote:remote,
              loading: false,
              options: [],
              value: ''
            },
            mounted(){
              if(!remote){
                this.axios.post(item.elDataRepo,{}).
                then(res=>{
                  this.options=res.data;
                });
              }
            },
            template:'<span><el-select v-model="value" filterable :remote="remote" :loading="loading" :remote-method="query" @change="change">'+
            '<el-option v-for="item in options" :key="item.value" :label="item.text" :value="'+valueDef+'"/></el-select></span>',
            methods: {
              query(param){
                 if (param !== '') {
                    this.loading = true;
                    this.axios.post(item.elDataRepo+'/'+param,{}).
                    then(res=>{
                      var result = res.data;
                      this.options = result;
                      this.loading = false;
                    });
                  } else {
                    this.options = [];
                  }
              },
              change(v){
                _this.result[id] = v;
              }
            }
          });
      },
      mounteDate(id, item) {
        let _this = this;
        this.$set(this.result, item.elId, '');
        let a = Vue.extend(DateProxy);
        new a({
          el: '#' + id,
          props: ['value'],
          parent: this,
          propsData: {
            value: _this.result[id],
            format: item.elFormat
          }
        }).$on('change', (val) => {
          _this.result[id] = val
        });
      },
      textWidth(val){
        var text = val+"1";
        var sensor = $('<pre>' + text + '</pre>').css({display: 'none'});
        $('body').append(sensor);
        var width = sensor.width();
        sensor.remove();
        if(width < 50) width = 50;
        return width;
      }
    }
  }
</script>

<style>
  #content-show .el-input,.ue-tag {
    width: 180px;
  }

  #content-show span {
    text-indent: 0px;
  }

  /* #content-show p>span:nth-child(1){
    text-indent: 28px;
  } */
  #content-show table {
    border-top: 1px solid #d2dcf8;
    border-right: 1px solid #d2dcf8;
  }

  #content-show table tr th,#content-show td {
    border-bottom: 1px solid #d2dcf8;
    border-left: 1px solid #d2dcf8;
    padding: 4px 6px;
  }

  #content-show .right-menu{
    display: flex;
    flex-direction: column;
    z-index: 99;
    background-color: #fff;
    width: 120px;
    border: 1px solid #d2dcf8;
    padding: 8px;
  }

   #content-show input{
    border-bottom: 1px solid #409EFF;
  }
</style>
